package com.qnnu.studenttravelsystem.controller;

import com.qnnu.studenttravelsystem.entity.Counselor;
import com.qnnu.studenttravelsystem.entity.Student;
import com.qnnu.studenttravelsystem.service.ICounselorService;
import com.qnnu.studenttravelsystem.service.IStudentService;
import com.qnnu.studenttravelsystem.service.impl.CounselorServiceImpl;
import com.qnnu.studenttravelsystem.service.impl.StudentServiceImpl;
import com.qnnu.studenttravelsystem.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName AuthController
 * @Description TODO
 * @Author zhongge
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    //教师的服务层
    @Autowired
    private ICounselorService counselorService;

    //学生的服务层
    @Autowired
    private IStudentService studentService;

    //JWT的token处理工具类
    @Autowired
    private JwtUtil jwtUtil;


    // 真实辅导员登录
    @PostMapping("/login/counselor")
    public Map<String, Object> loginCounselor(@RequestBody Map<String, String> req) {
        String staffNo = req.get("username");
        String password = req.get("password");

        Counselor counselor = counselorService.selectByStaffNo(staffNo);
        // 验证：用户存在 + 密码正确（先明文对比）
        if (counselor == null || !"123456".equals(password)) {
            throw new RuntimeException("工号或密码错误");
        }

        // 生成Token（存用户ID）
        String token = jwtUtil.generateToken(counselor.getId());
        Map<String, Object> res = new HashMap<>();
        res.put("token", token);
        res.put("name", counselor.getName());
        return res;
    }

    // 真实学生登录
    @PostMapping("/login/student")
    public Map<String, Object> loginStudent(@RequestBody Map<String, String> req) {
        String studentNo = req.get("username");
        String password = req.get("password");

        Student student = studentService.selectByStudentNo(studentNo);
        if (student == null || !"123456".equals(password)) {
            throw new RuntimeException("学号或密码错误");
        }

        String token = jwtUtil.generateToken(student.getId());
        Map<String, Object> res = new HashMap<>();
        res.put("token", token);
        res.put("name", student.getName());
        return res;
    }
}
